package com.itgaohe.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itgaohe.dao.entity.Chat;
import com.itgaohe.dao.mapper.ChatMapper;
import com.itgaohe.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements ChatService {

    @Autowired
    private  ChatMapper chatMapper;

    public List<Chat> getChatHistory(Long userId, Long friendId) {

        List<Chat> lists = new ArrayList<>();
        LambdaQueryWrapper<Chat> chatLambdaQueryWrapper = Wrappers.lambdaQuery(Chat.class)
                .eq(Chat::getFromId, userId)
                .eq(Chat::getToId, friendId)
                .orderByAsc(Chat::getTimestamp);
        List<Chat> chats = chatMapper.selectList(chatLambdaQueryWrapper);
        LambdaQueryWrapper<Chat> chatLambdaQueryWrapper1 = Wrappers.lambdaQuery(Chat.class)
                .eq(Chat::getFromId,  friendId)
                .eq(Chat::getToId, userId)
                .orderByAsc(Chat::getTimestamp);
        List<Chat> chats1 = chatMapper.selectList(chatLambdaQueryWrapper1);
        lists.addAll(chats);
        lists.addAll(chats1);
        lists.sort(Comparator.comparing(Chat::getTimestamp));
        return lists ;
    }

    @Override
    public Boolean sendMessage(Chat chat) {
        boolean save = this.save(chat);
        return save;
    }

}
